import { createClient } from '@supabase/supabase-js';
import { config } from '../config';
import { Node, Edge } from 'reactflow';

const supabaseUrl = config.supabaseUrl;
const supabaseKey = config.supabaseKey;

const supabase = createClient(supabaseUrl, supabaseKey);

export interface WorkflowData {
  workflow_id?: string;
  workflow_name: string;
  nodes: Node[];
  edges: Edge[];
}

export interface WorkflowItem {
  workflow_id: string;
  workflow_name: string;
  created_at: string;
}

export const workflowService = {
  saveWorkflow: async (data: WorkflowData) => {
    if (data.workflow_id) {
      const { data: result, error } = await supabase
        .from('workflows')
        .update(data)
        .eq('workflow_id', data.workflow_id)
        .single();
        
      if (error) throw new Error(error.message || '更新失败');
      return result;
    } else {
      const { data: result, error } = await supabase
        .from('workflows')
        .insert(data)
        .select()
        .single();
        
      if (error) throw new Error(error.message || '保存失败');
      return result;
    }
  },
  
  fetchWorkflowList: async (): Promise<WorkflowItem[]> => {
    const { data, error } = await supabase
      .from('workflows')
      .select('workflow_id,workflow_name,created_at')
      .order('created_at', { ascending: false });
      
    if (error) throw new Error(error.message || '请求失败');
    return data;
  },
  
  fetchWorkflowInfo: async (workflow_id: string) => {
    const { data, error } = await supabase
      .from('workflows')
      .select('*')
      .eq('workflow_id', workflow_id)
      .single();
      
    if (error) throw new Error(error.message || '请求失败');
    return data;
  },
  
  deleteWorkflow: async (workflow_id: string) => {
    const { error } = await supabase
      .from('workflows')
      .delete()
      .eq('workflow_id', workflow_id);
      
    if (error) throw new Error(error.message || '删除失败');
    return true;
  }
}; 